import os
import re
import time


# from AdminPermissionUtils import adminPermissionUtils


class hostsUtils:
    """
    该类用于修改系统hosts文件
    参考博客：python脚本修改hosts文件
    原文链接：https://www.cnblogs.com/guotianbao/p/8723568.html
    """
    def __init__(self,sys_hosts_file=os.path.join(os.environ["SystemRoot"],"System32","drivers","etc","hosts")):
        self.sys_hosts_file=sys_hosts_file
        self.create_path_file()
    def create_path_file(self):
        """
        如果hosts文件不存在创建文件
        :return:
        """
        namearr = re.split(r'[\\/]', self.sys_hosts_file)
        if len(namearr)<2:
            filename=os.path.join('.',self.sys_hosts_file)
            namearr = re.split(r'[\\/]', filename)
        pathstr = os.path.join(*namearr[:-1])

        if not os.path.exists(pathstr):
            print('创建目录：%s' % (pathstr))
            os.makedirs(pathstr)
        if not os.path.exists(self.sys_hosts_file):
            print('创建文件：%s' % (self.sys_hosts_file))
            f=open(self.sys_hosts_file,"w+",encoding="utf-8")
            f.close()

    def hosts_all_reader(self):
        """
        读取hosts全部内容，将每行内容存储为list一个条目
        :return: 返回包含hosts全部内容的list
        """
        contents=list()
        f=open(self.sys_hosts_file,"r+",encoding="utf-8")
        lines=f.readlines()
        for line in lines:
            line=line.strip()
            if len(line)==0:
                continue
            contents.append(line)
        f.close()
        return contents
    def hosts_all_writer(self,contents):
        """
        将contents内容保存到hosts中
        :param contents:包含待写入hosts全部内容的list
        :return:
        """
        f=open(self.sys_hosts_file,"w+",encoding="utf-8")
        print("清空hosts内容！")
        f.truncate(0)
        for content in contents:
            print("写入hosts内容：%s"%(content))
            f.write(content+"\n")
        f.close()
    def ip_to_dns_update(self,ip_list:list,dns_list:list):
        """
        更新IP对应的DNS值
        :param ip_list: IP列表
        :param dns_list: DNS列表
        :return: 更新成功失败
        """
        if len(ip_list)!=len(dns_list):
            return False
        print("读取hosts内容……")
        contents=self.hosts_all_reader()
        print("原hosts内容:%s"%contents)
        contents_new=contents.copy()
        for ip_ind in range(len(ip_list)):
            ip=ip_list[ip_ind]
            has_ip_flag=False
            for content_ind in range(len(contents)):
                content=contents[content_ind]
                if content[0]=="#" or content[0]=='\ufeff':
                    continue
                else:
                    content_split=re.split("\s+",content)
                    ipaddr=content_split[0]
                    dnsname=content_split[1]
                    if ip==ipaddr:
                        contents_new[content_ind]=ip+" "+dns_list[ip_ind]
                        has_ip_flag=True
                        break
            if not has_ip_flag:
                contents_new.append(ip+" "+dns_list[ip_ind])
        self.hosts_all_writer(contents_new)
        print("hosts内容写入完成！")
    def dns_to_ip_update(self,dns_list:list,ip_list:list):
        """
        更新IP对应的DNS值
        :param ip_list: IP列表
        :param dns_list: DNS列表
        :return: 更新成功失败
        """
        if len(ip_list)!=len(dns_list):
            return False
        print("读取hosts内容……")
        contents=self.hosts_all_reader()
        contents_new=contents.copy()
        for dns_ind in range(len(dns_list)):
            dns=dns_list[dns_ind]
            has_ip_flag=False
            for content_ind in range(len(contents)):
                content=contents[content_ind]
                if content[0]=="#":
                    continue
                else:
                    content_split=re.split("\s+",content)
                    ipaddr=content_split[0]
                    dnsname=content_split[1]
                    if dns==dnsname:
                        contents_new[content_ind]=ip_list[dns_ind]+" "+dns
                        has_ip_flag=True
                        break
            if not has_ip_flag:
                contents_new.append(ip_list[dns_ind]+" "+dns)
        self.hosts_all_writer(contents_new)
        print("hosts内容写入完成！")
# def main():
#     # hostsutils=hostsUtils(sys_hosts_file=os.path.join(os.environ["SystemRoot"],"System32","drivers","etc","hosts1"))
#     hostsutils=hostsUtils(sys_hosts_file=os.path.abspath("hosts1"))
#     contents=hostsutils.hosts_all_reader()
#     ip_list=["1.1.1.1","1.2.3.4"]
#     dns_list=["test1","test2"]
#     hostsutils.ip_to_dns_update(ip_list,dns_list)
# if __name__ == '__main__':
#     try:
#         main()
#     except PermissionError as e:
#         print(e)
#         adminPermissionUtils.AdminExecutor(__file__)
